package com.situ.stmall.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.situ.stmall.entity.User;
import com.situ.stmall.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@GetMapping("/reg")
	public String reg() {
		return "user/reg";
	}

	/**
	 * 用户注册
	 */
	@PostMapping("/reg")
	public String reg(User user, String repassword, 
			Model model) {
		//1获取参数
		//2调用server层
		int result = userService.reg(user, repassword);
		//3跳转页面
		if (result > 0) {
			//注册成功
			//跳转登录页面
			return "redirect:login";
		}else {
			//传递错误信息
			String error = "未知错误，联系管理员";
			if (result == -1) {
				error="账号格式不正确";
			}else if (result == -2) {
				error="密码格式不正确";
			}else if (result == -3) {
				error="两次密码不一致";
			}else if (result == -4) {
				error="账号不可用";
			}
			model.addAttribute("error", error);
			//跳转注册页面, 请求转发
			return "user/reg";
		}
	}
	
	/**
	 * 登录的页面
	 * @return
	 */
	@GetMapping("/login")
	public String login() {
		return "user/login";
	}
	/**
	 * 登录处理
	 * @param user
	 * @param model
	 * @param session
	 * @return
	 */
	@PostMapping("/login")
	public String login(User user, Model model, HttpSession session) {
		//参数
		//service
		try {
			user = userService.login(user);
			
			//登录成功
			//保存用户信息到session
			session.setAttribute("user", user);
			//跳转主页面
			return "redirect:/";
		} catch (Exception e) {
			e.printStackTrace();
			//登录失败
			model.addAttribute("error", e.getMessage());
			//回到登录页面
			return "user/login";
		}
		
	}
	
	/**
	 * 退出登录
	 */
	@GetMapping("/logout")
	public String logout(HttpSession session) {
		//清除session
		session.invalidate();
		
		//跳转页面
		return "redirect:/";
	}
	

}
